import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:example/bean/template_element_entity.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_scaffold/flutter_scaffold.dart';
import 'package:archive/archive.dart';
import 'package:archive/archive_io.dart';

class WebviewDemoPage extends StatefulWidget {
  const WebviewDemoPage({super.key});

  @override
  State<WebviewDemoPage> createState() => _WebviewDemoPageState();
}

class _WebviewDemoPageState extends State<WebviewDemoPage> {
  var webController = WebViewController();
  Uint8List? bytes = null;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    webController.loadFlutterAsset("assets/html/template.html");
    webController.setJavaScriptMode(JavaScriptMode.unrestricted);
    webController.addJavaScriptChannel(
      'DataHandler',
      onMessageReceived: (message) {
        List<dynamic> map = jsonDecode(message.message);
        for (var item in map) {
          Log.i(
            "left===>${jsonEncode(TemplateElement.fromJson(item)).toString()}",
          );
        }
      },
    );

    webController.addJavaScriptChannel(
      'captureHandler',
      onMessageReceived: (message) {
        var base64Image = message.message;
        String data = base64Image.replaceFirst(
          RegExp(r'data:image/[^;]+;base64,'),
          '',
        );
        bytes = base64.decode(data);
        final Map<String, dynamic> comp = {
          "id": "comp9",
          "type": "image",
          "img": base64Image,
          "style": {"left": "0", "top": "0", "width": "500px"},
        };
        webController.runJavaScript("updateOrInsertImg(${jsonEncode(comp)})");
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("webview")),
      body: Container(
        width: double.infinity,
        margin: EdgeInsets.all(20.w),
        height: Get.height * 0.6,
        child: WebViewWidget(controller: webController),
      ),
      floatingActionButton: Row(
        children: [
          TextButton(
            onPressed: () {
              final Map<String, dynamic> comp =
                  TemplateElement(
                    id: "text_4",
                    text: "黄智波",
                    type: ElementType.text.name,
                    style: Style(
                      left: 30,
                      top: 20,
                      width: 200,
                      fontSize: 40,
                      textColor: "#ff0000",
                    ),
                  ).toJson();
              webController.runJavaScript(
                "updateOrInsertText(${jsonEncode(comp)})",
              );
            },
            child: Text("插入文本"),
          ),

          TextButton(
            onPressed: () {
              webController.runJavaScript("capture()");
            },
            child: Text("截图画布"),
          ),

          TextButton(
            onPressed: () {
              webController.runJavaScriptReturningResult("downloadHTML()").then(
                (value) {
                  Log.i(jsonDecode(value as String));
                },
              );
            },
            child: Text("保存当前html"),
          ),
        ],
      ).marginAll(20.w),
    );
  }

  /// 拷贝 assets 中的 zip 文件并解压到 files 目录
  Future<void> copyAndUnzipAsset(
    String assetZipPath, {
    String? outputFolderName,
  }) async {
    // 1. 加载 zip 文件数据
    final byteData = await rootBundle.load(assetZipPath);
    final bytes = byteData.buffer.asUint8List();

    // 2. 获取应用 file 目录（ApplicationSupportDirectory 对应 Android 的 /data/data/<pkg>/files）
    final appDir = await getApplicationSupportDirectory();
    final outputDir = Directory(
      outputFolderName == null
          ? appDir.path
          : '${appDir.path}/$outputFolderName',
    );
    await outputDir.create(recursive: true);

    // 3. 解压 zip 数据
    final archive = ZipDecoder().decodeBytes(bytes);
    for (final file in archive) {
      final filePath = '${outputDir.path}/${file.name}';
      if (file.isFile) {
        final outFile = File(filePath);
        await outFile.parent.create(recursive: true);
        await outFile.writeAsBytes(file.content as List<int>);
      } else {
        await Directory(filePath).create(recursive: true);
      }
    }

    print('解压完成：${outputDir.path}');
  }
}
